package com.common.library.ui.view.pager;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

/**
 * ViewPager 线条选择器
 */
public class ViewPagerLineIndicator  extends LinearLayout {
    private Paint mpaint;//画笔
    private int PAINT_COLOR = Color.parseColor("#80afacac");//指示器颜色
    private int m0ffsettX;//滑动的偏移量
    private int mTabVisibleCount;//可见tab数量
    private static final int COUNT_DEFAULT_TAB = 4;//默认可见显示Tab数量
    private List<String> mTitles;//Tab的文本集合
    private int COLOR_TEXT_DARK = Color.parseColor("#80000000");//Tab文本未选中的颜色
    private int COLOR_TEXT_LIGHT = Color.parseColor("#000000");//Tab文本选中的颜色
    private int TAB_TEXT_SIZE = 18;//Tab字体大小sp

    public ViewPagerLineIndicator(Context context) {
        this(context, null);
    }
    public ViewPagerLineIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取用户设置的可见Tab的数量
//        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
//        mTabVisibleCount = a.getInt(R.styleable.ViewPagerIndicator_visible_tab_count, COUNT_DEFAULT_TAB);
//        if (mTabVisibleCount < 0) {
//            mTabVisibleCount = COUNT_DEFAULT_TAB;
//        }
//        a.recycle();
    }
    private int POINTER_WIDTH = 50;//线条的默认宽度
    private int mWidth;//线条的宽度
    private int mStartX;//绘制线条开始的X轴
    private int mStartY;//绘制线条开始的Y轴
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = POINTER_WIDTH;
        mStartX = (getScreenWidth()/mTabVisibleCount/2)-(mWidth/2);
        mStartY = h-1; //距离
    }
    @Override
    protected void dispatchDraw(Canvas canvas) {
        if (mpaint != null) {
            canvas.save();
            canvas.translate(m0ffsettX, 0);
            canvas.drawLine(mStartX,mStartY,mStartX+mWidth,mStartY,mpaint);
            canvas.restore();
        }
        super.dispatchDraw(canvas);
    }
    /**
     * 确定显示子View的个数
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int cCount = getChildCount();
        if (cCount == 0) return;
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            LayoutParams lp = (LayoutParams) view.getLayoutParams();
            lp.weight = 0;
            lp.width = getScreenWidth() / mTabVisibleCount;
            view.setLayoutParams(lp);
        }
    }
    /**
     * 初始化
     */
    private void init() {
        mpaint = new Paint();
        mpaint.setAntiAlias(true);
        mpaint.setColor(PAINT_COLOR);
        mpaint.setStyle(Paint.Style.STROKE);
        mpaint.setPathEffect(new CornerPathEffect(3));
        mpaint.setStrokeWidth(10.0f);
    }
    /**
     * 设置指示器移动距离
     */
    public void setScroll(int position, float positionOffset) {
        int tabwidth = getScreenWidth()/ mTabVisibleCount;
        m0ffsettX = (int) (tabwidth * (position + positionOffset));
        postInvalidate();
    }
    /**
     * 设置Tab点击事件
     */
    private void setClickTabEvent(int count) {
        for (int i = 0; i < count; i++) {
            final int pos = i;
            final View view = getChildAt(i);
            if (view instanceof TextView) {
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(pos, false);
                    }
                });
            }
        }
    }
    /**
     * 获得屏幕的宽度
     */
    private int getScreenWidth() {
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }
    /**
     * @param tabVisibleCount 设置Tab可见数量
     */
    public void setTabVisibleCount(int tabVisibleCount) {
        mTabVisibleCount = tabVisibleCount;
    }
    /**
     * @param titles 根据titles设置Tab
     */
    public void setTabItemTitles(List<String> titles) {
        if (titles != null && titles.size() > 0) {
            this.removeAllViews();
            mTitles = titles;
            for (String title : mTitles) {
                if (!title.equals("") && title != null)
                    addView(getTextView(title));
            }
            if (getChildCount() != 0) {
                init();
                setClickTabEvent(getChildCount());
            }
        }
    }
    /**
     * @param textSize  Tab字体大小  单位为SP
     * @param SeletedTextColor  Tab选中时字体的颜色
     * @param  textColor  Tab未选中时字体的颜色
     * @param indictorColor 指示器颜色
     * @param indictorWidth 指示器的宽度
     * */
    public void setTabProperty(int textSize,int SeletedTextColor,int textColor,int indictorColor ,int indictorWidth ){
        TAB_TEXT_SIZE = textSize > 0 ? textSize:TAB_TEXT_SIZE;
        COLOR_TEXT_DARK = textColor == 0 ? COLOR_TEXT_DARK:textColor;
        COLOR_TEXT_LIGHT = SeletedTextColor == 0 ? COLOR_TEXT_LIGHT:SeletedTextColor;
        PAINT_COLOR = indictorColor == 0 ? PAINT_COLOR:indictorColor;
        POINTER_WIDTH = indictorWidth == 0 ? POINTER_WIDTH:indictorWidth;
    }


    /**
     * @param title 根据title 返回TextView实例
     */
    private View getTextView(String title) {
        LayoutParams lp = new LayoutParams(getScreenWidth() / mTabVisibleCount, LayoutParams.MATCH_PARENT);
        TextView tv = new TextView(getContext());
        //字体加粗
        tv .setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

        tv.setTextColor(COLOR_TEXT_DARK);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_TEXT_SIZE);
        tv.setGravity(Gravity.CENTER);
        tv.setText(title);
        tv.setLayoutParams(lp);
        return tv;
    }
    /**
     * 重置文本颜色
     */
    private void ResetTextColor() {
        int Ccount = getChildCount();
        for (int i = 0; i < Ccount; i++) {
            View view = getChildAt(i);
            if (view instanceof TextView) {
                ((TextView) view).setTextColor(COLOR_TEXT_DARK);
            }
        }
    }
    /**
     * @param pos 设置某一个Tab文本的颜色为高亮
     */
    private void setTextLightColor(int pos){
        if (getChildCount() == 0) return;
        ResetTextColor();
        View view = getChildAt(pos);
        if (view instanceof TextView) {
            ((TextView) view).setTextColor(COLOR_TEXT_LIGHT);
        }
    }
    private OnPageChangeListener mPageChangeListener;
    private ViewPager mViewPager;
    /**
     * ViewPager Item选择监听接口
     */
    public interface OnPageChangeListener {
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
        public void onPageSelected(int position);
        public void onPageScrollStateChanged(int state);
    }
    /**
     * @param pageChangeListener 设置ViewPager Item选择监听
     */
    public void addOnPageChangeListener(OnPageChangeListener pageChangeListener) {
        mPageChangeListener = pageChangeListener;
    }
    /**
     * 设置ViewPager
     * @param pos 默认显示item的位置
     */
    @SuppressWarnings("deprecation")
    public void setViewPager(ViewPager viewPager, int pos) {

        mViewPager = viewPager;
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (getChildCount() != 0) {
                    setScroll(position, positionOffset);
                }
                if (mPageChangeListener != null) {
                    mPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
            }
            @Override
            public void onPageSelected(int position) {
                setTextLightColor(position);
                if (mPageChangeListener != null) {
                    mPageChangeListener.onPageSelected(position);
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {
                if (mPageChangeListener != null) {
                    mPageChangeListener.onPageScrollStateChanged(state);
                }
            }
        });
        mViewPager.setCurrentItem(pos);
        setTextLightColor(pos);
    }
}
